<?php
/**
 * 平台订单
 * Date: 2024/12/5
 * Time: 16:25
 */

namespace App\Logic\Plat;

use App\Logic\Amazon\Api\CustomerOutbound;
use App\Logic\Amazon\Api\RequiredConfig;
use App\Logic\Plat\Rakuten\Overseas\GuCang\Order\OverseasOrder;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\OverSeasBa\DropshippingInventoryFnsku;
use App\Models\Product\ProductRakutenSku;
use App\Models\Product\ProductSku;
use App\Models\Rakuten\RakutenOrder;

class SyncPlatOrder{

    /**
     * erp未发货订单同步至第三方平台
     * @param array $orderIds
     * @param bool $isOpenStock
     * @throws \Exception
     */
    public static function syncCustomerOrder($orderIds = [],$isOpenStock = true){

        //rakuten未同步订单
        $query = CustomerOrder::query();
        $query->where('plat_id', SysPlat::PLAT_RAKUTEN); //日本乐天平台
        $query->where('sync_status', CustomerOrder::SYNC_NO);  //未同步
        $query->where('order_at', '>=', '2024-12-12 00:00:00');
        if(!empty($orderIds)){
            $query->whereIn('order_no', $orderIds);
        }
        $customerOrders = $query->orderBy('id')->get();
        if (!$customerOrders) dd('over!');

        foreach($customerOrders as $customerOrder){
            $rakutenOrder = RakutenOrder::query()->where('order_id',$customerOrder->order_no)->first();
            if (!$rakutenOrder) continue;
            $orderNo = $rakutenOrder->order_id;

            //验证Rakuten产品类型
            $isOsWarehouseSkuFlag = false;
            foreach ($rakutenOrder->rakuten_orders_items as $_k => $_v) {
                $isOsWarehouse = ProductRakutenSku::getValueByCode($_v->platform_sku, 'is_os_warehouse');  //是否为海外仓产品(1:是 2:否)
                if ($isOsWarehouse) {
                    if ($isOsWarehouse == ProductRakutenSku::OS_WAREHOUSE_NO){
                        $isOsWarehouseSkuFlag = false; //非海外仓产品
                        break;
                    }
                    $isOsWarehouseSkuFlag = true; //海外仓产品
                }
            }

            /****订单同步至第三方平台（海外仓、FBA）****/
            //一：海外仓产品 (海外仓库存(海外仓订单)(海外仓发货))
            if ($isOsWarehouseSkuFlag == true) {
                $dropshippingInventoryFlag = DropshippingInventoryFnsku::_checkDropshippingInventoryFnsku($rakutenOrder);
                if ($dropshippingInventoryFlag == true) {
                    //API验证谷仓海外仓订单是否存在
                    $overseasOrder = OverseasOrder::getReferenceOrder($orderNo);
                    if ($overseasOrder) continue;

                    //客户订单发货
                    $customerDeliveryFlag = CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_ABROAD,200000);
                    if (!$customerDeliveryFlag) continue;
                    sleep(1);

                    //更新JP-海外代发库存
                    if ($isOpenStock == true) {
                        DropshippingInventoryFnsku::_saveDropshippingInventoryFnsku($rakutenOrder);
                    }
                }
            }

            /*//二：非海外仓产品((FBA、国内订单)(FBA、国内发货))
            if ($isOsWarehouseSkuFlag == false) {
                //验证：FBA库存(非海外仓订单)(FBA发货)
                list($fbaInventoryFlag,$accountId) = FBAInventory::_checkJpFbaInventoryFnsku($rakutenOrder);
                if ($fbaInventoryFlag == true) {
                    //API验证Amazon订单是否存在
                    $fulfillmentOrder = CustomerOutbound::getFulfillmentOrder($orderNo,$accountId);
                    if ($fulfillmentOrder) continue;

                    //客户订单发货
                    $customerDeliveryFlag = CustomerOrder::addCustomerDelivery($rakutenOrder,CustomerDelivery::DELIVERY_TYPE_FBA,$accountId);
                    if (!$customerDeliveryFlag) continue;
                    sleep(1);

                    //更新JP-FBA库存
                    if ($isOpenStock == true) {
                        FBAInventory::_saveJpFbaInventoryFnsku($rakutenOrder);
                    }
                }
            }*/
            /****乐天订单同步至海外仓（海外仓、FBA）****/
        }
    }

    /**
     * erp未发货订单同步至第三方平台（同步异常，超时）
     * @param $seller_fulfillment_order_id
     * @param $accountId
     */
    public static function deliveryOrderException($seller_fulfillment_order_id,$accountId){
        $query = CustomerDelivery::query();
        $query->where('delivery_type',[CustomerDelivery::DELIVERY_TYPE_FBA,CustomerDelivery::DELIVERY_TYPE_ABROAD]); //发货方式
        $query->where('plat_sync_status', 1); //发货订单未上传至平台
        $query->where('status', '<=', 5); //发货状态
        $query->where('created_at', '<=', strtotime('-3 days')); //超时时间
        if ($seller_fulfillment_order_id != 'null') {
            $query->where('order_no', $seller_fulfillment_order_id);
        }
        $customerDelivery = $query->get();
        if ($customerDelivery->isNotEmpty()){

            foreach ($customerDelivery as $index => $deliveryOrder){
                if (!$deliveryOrder) continue;
                if (!$deliveryOrder->detail) continue;

                $deliveryOrderDetail = $deliveryOrder->detail;
                if (intval($accountId) > 0) {
                    $deliveryOrderDetail = $deliveryOrder->detail->where('account_id',$accountId);
                }
                if (!$deliveryOrderDetail || $deliveryOrderDetail->isEmpty()) continue;

                //发货单
                $deliveryOrder->status = 6; //发货状态：异常
                $deliveryOrder->save();

                //发货单明细
                foreach ($deliveryOrderDetail as $key => $val){
                    $val->status = 6;
                    $val->save();
                }
            }
        }
    }

    /**
     * (Amazon)
     * 客户订单同步至Amazon多渠道
     * @param $seller_fulfillment_order_id
     * @param $accountId
     */
    public static function syncCreateAmazonOrder($seller_fulfillment_order_id,$accountId){

        $query = CustomerDelivery::query();
        $query->where('delivery_type',CustomerDelivery::DELIVERY_TYPE_FBA); //Amazon-FBA发货方式
        $query->where('status', '<=', 5); //发货状态
        $query->where('plat_sync_status', 1); //发货订单未上传至平台
        $query->where('created_at', '>=', '2024-11-01 00:00:00');
        if ($seller_fulfillment_order_id != 'null') {
            $query->where('order_no', $seller_fulfillment_order_id);
        }
        $query->chunk(100,function ($items) use ($accountId){
            foreach ($items as $deliveryOrder){
                if ($deliveryOrder->detail->isEmpty()) continue;

                $deliveryOrderDetail = $deliveryOrder->detail;
                if (intval($accountId) > 0) {
                    $deliveryOrderDetail = $deliveryOrder->detail->where('account_id',$accountId);
                }
                if ($deliveryOrderDetail->isEmpty()) continue;

                //组装请求参数
                $paramData = [];
                foreach ($deliveryOrderDetail as $key => $val){
                    $paramData[$key]['delivery_order_no'] = $val->delivery_order_no;
                    $paramData[$key]['account_id'] = $val->account_id;
                }
                if (!$paramData) continue;

                $flag = false;
                //推送客户订单至Amazon(多渠道发货)
                foreach ($paramData as $index => $param){
                    $deliveryOrderNo = $param['delivery_order_no']; //实际发货订单号
                    $platAccountId = $param['account_id']; //平台发货账号id
                    $orderFlag = CustomerOutbound::apiCreateFulfillmentOrder($deliveryOrder,$deliveryOrderNo,$platAccountId);
                    if (!$orderFlag) break;
                    $flag = true;
                }

                if ($flag) {
                    //更新发货单
                    $deliveryOrder->plat_sync_status = 2; //已上传至平台
                    $deliveryOrder->plat_sync_at = date('Y-m-d H:i:s', time());
                    $deliveryOrder->save();
                    sleep(1);
                }
            }
        });
    }

    /**
     * (Amazon)
     * 批量,获取amazon追踪号(每天)(Amazon物流回写至Erp客户发货订单)
     * @param $deliveryOrderNo
     * @param $accountId
     * @throws \Exception
     */
    public static function syncAmazonTrackingNo($deliveryOrderNo,$accountId){

        $query = CustomerDeliveryDetail::query();
        //$query->where('plat_id', SysPlat::PLAT_AMAZON); //Amazon平台
        $query->where('status', '<=', 5); //发货状态
        $query->where('delivery_type',CustomerDelivery::DELIVERY_TYPE_FBA); //Amazon-FBA发货方式
        $query->where('sync_status',0); //Amazon物流信息未同步
        $query->where('created_at', '>=', '2024-11-01 00:00:00');
        if ($deliveryOrderNo != 'null') {
            $query->where('delivery_order_no', $deliveryOrderNo);
        }
        if ($accountId > 0) {
            $query->where('account_id', $accountId);
        }
        $customerDeliveryDetail = $query->get();
        if ($customerDeliveryDetail->isNotEmpty()) {
            $accountArr = [];
            foreach($customerDeliveryDetail as $key => $detail){
                $paltAccountId = $detail->account_id; //发货账号
                $sellerFulfillmentOrderId = $detail->delivery_order_no; //实际发货订单号
                if(!array_key_exists($paltAccountId, $accountArr)){
                    $accountArr[$paltAccountId] = AmazonAccount::query()->find($paltAccountId);
                }
                $account = $accountArr[$paltAccountId];
                $requiredConfig = RequiredConfig::getInit();
                $config = $requiredConfig->configuration($account->refresh_token, $account->aws_region);
                CustomerOutbound::apiGetFulfillmentOrder($config,$account,$sellerFulfillmentOrderId);
                sleep(1);
            }
        }
    }

    /**
     * 海外仓(谷仓)
     * 客户订单同步至海外仓(谷仓)
     * @param $seller_fulfillment_order_id
     * @param $accountId
     */
    public static function syncCreateRakutenOrder($seller_fulfillment_order_id,$accountId){

        $query = CustomerDelivery::query();
        $query->where('delivery_type',CustomerDelivery::DELIVERY_TYPE_ABROAD); //海外仓发货方式
        $query->where('status', '<=', 5); //发货状态
        $query->where('plat_sync_status', 1); //发货订单未上传至平台
        $query->where('created_at', '>=', '2024-11-01 00:00:00');
        if ($seller_fulfillment_order_id != 'null') {
            $query->where('order_no', $seller_fulfillment_order_id);
        }
        $query->chunk(100,function ($items) use ($accountId){
            foreach ($items as $deliveryOrder){
                if ($deliveryOrder->detail->isEmpty()) continue;

                $deliveryOrderDetail = $deliveryOrder->detail;
                if (intval($accountId) > 0) {
                    $deliveryOrderDetail = $deliveryOrder->detail->where('account_id',$accountId);
                }
                if ($deliveryOrderDetail->isEmpty()) continue;

                //临时条件(过滤预售订单)(可删除)
                foreach ($deliveryOrderDetail as $key => $val){
                    $pskuCode = ProductSku::getValueById($val->psku_id,'psku_code');
                    if (in_array($pskuCode,['AM05116', 'AM05115', 'AM05112', 'AM05111', 'AM04208',
                        'AM04207', 'AM05120', 'AM05119', 'AM03886', 'AM04165',
                        'AM03884', 'AM03885', 'AM04164'])) {
                        break;
                    }
                }

                //组装请求参数
                $paramData = [];
                foreach ($deliveryOrderDetail as $key => $val){
                    $paramData[$key]['delivery_order_no'] = $val->delivery_order_no;
                    $paramData[$key]['account_id'] = $val->account_id;
                }
                if (!$paramData) continue;

                $flag = false;
                //推送客户订单至Amazon(多渠道发货)
                foreach ($paramData as $index => $param){
                    $deliveryOrderNo = $param['delivery_order_no']; //实际发货订单号
                    $platAccountId = $param['account_id']; //平台发货账号id
                    $orderFlag = OverseasOrder::createOrder($deliveryOrder,$deliveryOrderNo,$platAccountId);
                    if (!$orderFlag) break;
                    $flag = true;
                }

                if ($flag) {
                    //更新发货单
                    $deliveryOrder->plat_sync_status = 2; //已上传至平台
                    $deliveryOrder->plat_sync_at = date('Y-m-d H:i:s', time());
                    $deliveryOrder->save();
                    sleep(1);
                }
            }
        });
    }

    /**
     * 海外仓(谷仓)
     * 批量,获取海外仓追踪号(每天)(海外仓(谷仓)物流回写至Erp客户发货订单)
     * @param null $deliveryOrderNo
     * @param null $startTime
     * @param null $endTime
     */
    public static function syncRakutenGuCangTrackingNo($deliveryOrderNo = null,$startTime = null,$endTime = null){
        //客户订单发货明细
        $query = CustomerDeliveryDetail::query();
        //$query->where('plat_id', SysPlat::PLAT_RAKUTEN); //乐天平台
        $query->where('status', '<=', 5); //发货状态
        $query->where('delivery_type', CustomerDelivery::DELIVERY_TYPE_ABROAD); //2：海外仓
        $query->where('sync_status', 0); //0：平台物流未同步
        $query->where('is_sync_rakuten', 0); //0：乐天物流未同步
        $query->where('created_at', '>=', '2024-11-01 00:00:00');
        if ($deliveryOrderNo != 'null') {
            $query->where('delivery_order_no', $deliveryOrderNo);
        }
        $deliveryDetailList = $query->get();
        if ($deliveryDetailList->isNotEmpty()){
            foreach ($deliveryDetailList as $key => $val){
                $overseasOrder = OverseasOrder::getReferenceOrder($val->delivery_order_no);
                if ($overseasOrder) {
                    if ($overseasOrder->order_code) {
                        OverseasOrder::updateOrderInfo($overseasOrder->order_code,$startTime,$endTime);
                    }
                }
            }
        }
    }

}
